<template>
  <div id="dialogPubJob">
    <el-dialog
      class="about-set"
      title="修改我的作业"
      :visible.sync="dialogData.isShow"
      width="600px"
      top="20px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          v-loading="formLoading"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="选择学院">
            <el-select
              v-model="ruleForm.categoryId"
              disabled
              placeholder="选择学院"
            >
              <el-option
                v-for="item in collegeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <showTagSelect
            ref="tagSelect"
            :channel="channel"
            @getTagIds="getTagIds"
            :isCanNotEdit="true"
          ></showTagSelect>
          <el-form-item label="选择马甲">
            <el-select
              v-model="ruleForm.userId"
              disabled
              placeholder="请选择马甲"
            >
              <el-option
                v-for="item in vestList"
                :key="item.robotId"
                :label="item.robotName"
                :value="item.robotId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择课程">
            <el-select
              v-model="ruleForm.courseTitle"
              disabled
              placeholder="请选择课程"
            ></el-select>
          </el-form-item>
          <el-form-item label="选择期">
            <el-select
              v-model="ruleForm.courseChannelTitle"
              disabled
              placeholder="请请选择期"
            ></el-select>
          </el-form-item>
          <el-form-item label="作业类型">
            <el-radio-group v-model="ruleForm.jobType" disabled>
              <el-radio
                v-for="item in typeList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择作业">
            <el-select
              v-model="ruleForm.taskTitle"
              disabled
              placeholder="请选择章节列表"
            ></el-select>
          </el-form-item>
          <el-form-item label="作业内容" prop="jobContent">
            <el-input
              v-model="ruleForm.jobContent"
              type="textarea"
              maxlength="60"
              show-word-limit
            ></el-input>
          </el-form-item>
          <!--作业类型为图文-->
          <el-form-item
            v-show="ruleForm.jobType === 'TEXT'"
            label="添加作业"
            prop="imgInfo"
          >
            <uploadImg
              :img-info="ruleForm.imgInfo"
              @setImgInfo="setImgInfo"
            ></uploadImg>
          </el-form-item>
          <!--作品类型为小视频-->
          <el-form-item
            v-show="ruleForm.jobType === 'VIDEO'"
            label="添加作业"
            prop="vid"
          >
            <el-button id="upload" type="warning">
              上传视频
            </el-button>
            <span class="red-note">注：视频最长限制3分钟</span>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEditJobDetail, pubEditJob } from '@/api/jobManagement' // 接口
import uploadImg from '@common/uploadImg' // 上传图片公共组件
import showTagSelect from '@common/showTagSelect' // 显性标签下拉选择公共组件
import { getVideoPara } from '@utils/pubFunction'
import { uploadVideo } from '@utils/uploadVideo'
import { sysNormalDisable, getVestList } from '@utils/dictionariesFunc'
export default {
  name: 'DialogPubJob',
  msg: '作业管理-我的发布---修改作业',
  components: {
    uploadImg,
    showTagSelect
  },
  props: ['dialogData'],
  data() {
    return {
      id: '',
      loading: false, // 确认按钮的loading
      formLoading: true, // 表单加载的loading
      collegeList: [], // 学院
      vestList: [], // 选择马甲
      typeList: [], // 作业类型
      ruleForm: {
        categoryId: '', // 学院
        userId: '', // 马甲
        courseChannelTitle: '', // 期
        courseTitle: '', // 课程
        jobType: '', // 作业类型 与作业任务一致 TEXT 图片|VIDEO 视频
        taskTitle: '', // 选择作业
        jobContent: '', // 作业内容
        imgInfo: '' // 图片
      },
      imgInfo: [], // 用来接收数组图片
      rules: {
        taskId: { required: true, message: '请选择作业任务' },
        jobContent: {
          required: true,
          message: '作业内容不能为空',
          trigger: 'change'
        },
        imgInfo: { required: true, message: '请上传作业图片' },
        vid: { required: true, message: '请上传作业视频' }
      },
      jobDetailData: {
        isShow: false, // 默认隐藏
        params: '' // 编辑时，传递的参数
      },
      polivNum: {
        polyvUserId: '',
        polyvSecretKey: '',
        polyvWriteToken: '',
        polyvReadToken: ''
      },
      upVideo: null,
      channel: 'JOB',
      labelItems: []
    }
  },
  computed: {
    dapengUserId() {
      return this.$store.state.user.dapengUserId
    }
  },
  watch: {
    'ruleForm.jobType': {
      // 监听类型
      handler(newValue, oldValue) {
        let channel = ''
        if (newValue === 'VIDEO') {
          // 视频
          this.rules.imgInfo = {}
          this.rules.vid = { required: true, message: '请上传视频' }
          channel = 'SHORT_VIDEO'
        } else {
          // 图文
          this.rules.imgInfo = { required: true, message: '请上传作业图片' }
          this.rules.vid = {}
          channel = 'JOB'
        }
        this.$refs.tagSelect.getTagList(channel)
        //标签数据回填
        this.$refs.tagSelect.setValueTagIds(this.labelItems)
      },
      deep: true
    }
  },
  mounted() {
    this.getStatusList()
    this.id = this.dialogData.id
    this.getFormData()
    this.getPolivNum()
  },
  methods: {
    /* 获取系统配置-保利威视 */
    getPolivNum() {
      let _this = this
      getVideoPara().then((data) => {
        this.polivNum = { ...data }
        uploadVideo(_this.polivNum, _this.saveVideo).then((resObj) => {
          _this.upVideo = resObj
        })
      })
    },
    /* 获取数据状态 */
    async getStatusList() {
      // 作业类型
      this.typeList = await sysNormalDisable('sys_task_type')
      // 学院
      this.collegeList = await sysNormalDisable('sys_college')
      this.ruleForm.collegeId = this.collegeList[0].dictValue
      // 马甲
      this.vestList = await getVestList(this.dapengUserId)
    },
    /* 获取表单详情 */
    getFormData() {
      this.formLoading = true
      getEditJobDetail(
        this.id,
        (response) => {
          this.ruleForm = { ...response }
          this.imgInfo = response.imgInfo ? JSON.parse(response.imgInfo) : []
          delete this.ruleForm.labelInfos
          this.labelItems = response.labelInfos || []
          this.formLoading = false
        },
        (response) => {
          this.$message({
            message: '获取详情失败，' + response.message,
            type: 'warning'
          })
          this.formLoading = false
        }
      )
    },
    /* 保存上传视频 */
    async saveVideo(fileData) {
      this.ruleForm.vid = fileData.vid
    },
    /* 图片上传成功后，获取返回结果 */
    setImgInfo(ary) {
      this.imgInfo = ary //返回为数组
      this.ruleForm.imgInfo = ary.length > 0 ? JSON.stringify(ary) : ''
    },
    /*整合选择的标签*/
    setIabelInfos() {
      let ary = []
      this.labelItems.forEach((item, index) => {
        let { labelCategoryProperty, labelId, labelName } = item
        let obj = {
          labelCategoryProperty,
          labelId,
          labelName
        }
        ary.push(obj)
      })
      return [...ary]
    },
    /* 确认提交 */
    confirmLabel(formName) {
      this.loading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let homeId = this.ruleForm.jobcompletionId
          let userId = this.ruleForm.userId
          let type = this.ruleForm.jobType
          let content = this.ruleForm.jobContent
          let imgInfo = this.imgInfo
          let vid = this.ruleForm.vid ? this.ruleForm.vid : ''
          let labelInfos = this.ruleForm.labelInfos
          let obj = { userId, type, content, imgInfo, vid, labelInfos }
          //选中标签
          obj.labelInfos = this.setIabelInfos()
          pubEditJob(
            homeId,
            obj,
            (response) => {
              this.loading = false
              this.$emit('refresh')
              this.cancelLabel()
            },
            (response) => {
              this.loading = false
              this.$message.warning('修改作业失败，' + response.message)
            }
          )
        } else {
          this.loading = false
          return false
        }
      })
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.id = null
      // this.dialogData.postId = null
      clearInterval(this.upVideo.timer)
      this.upVideo.destroy()
      this.dialogData.isShow = false
    },
    /* 获取选中的显性标签 */
    getTagIds(items) {
      this.labelItems = [...items]
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less">
#dialogPubJob {
  @import url('~@common/style/textarea.less');
  .red-note {
    padding-left: 10px;
    color: #f00;
  }
  button.el-button.el-button--default.is-plain {
    width: 100%;
  }
  .el-form-item__error {
    padding: 0;
  }
  .el-dialog__wrapper {
   /* z-index: 3000 !important;*/
  }
}
</style>
